<?php
/**
 *
 * @author 孙春雷
 * 对入库表的数据库操作
 */
class Model_Warehouseorders extends Modelnewerp {
	
	// 数据库所有字段变量
	protected $id = 'id';
	const warehouse_date = 'warehouse_date';
	const op_time = 'op_time';
	const purchaseorders_id = 'purchaseorders_id';
	const returned_parcel_id = 'returned_parcel_id';
	const check_quality_detail_id = 'check_quality_detail_id';
	const supplier_id = 'supplier_id';
	const department = 'department';
	const sku = 'sku';
	const sku_name = 'sku_name';
	const sku_standard = 'sku_standard';
	const storage_position = 'storage_position';
	const warehouse_quantity = 'warehouse_quantity';
	const tax_way = 'tax_way';
	const single_price = 'single_price';
	const money = 'money';
	const tax_price = 'tax_price';
	const cost = 'cost';
	const remark = 'remark';
	const transportation_expense = 'transportation_expense';
	const status = 'status';
	const type = 'type';
	const warehouse_man = 'warehouse_man';

	/**
	 * 调用的数据表
	 *
	 * @var unknown
	 */
	protected $_table = 'warehouseorders';

	/**
	 * 根据时间段和sku获取入库存总的数量和成本
	 *
	 * @param unknown $starttime        	
	 * @param unknown $endtime        	
	 * @param string $sku        	
	 * @return Ambigous <multitype:, multitype:unknown NULL >
	 */
	public function getCountAndCost($starttime, $endtime, $sku = NULL)
	{
		// 定义结果数组
		$result = array ();
		
		// 统计入库的数量和成本
		$sql = DB::select( array (
				self::sku,
				'sku' 
		), array (
				DB::expr( "sum(" . self::warehouse_quantity . ")" ),
				'count' 
		), array (
				DB::expr( "sum(" . self::cost . ")" ),
				'cost' 
		) )->from( $this->_table )
			->where( self::warehouse_date, '>=', $starttime )
			->where( self::warehouse_date, '<', $endtime . ' 23:59:59' );
		if ($sku)
		{
			$sql->where( self::sku, '=', $sku );
		}
		$sql->group_by( self::sku );
		$current_in = $sql->execute( $this->_db )
			->as_array();
		
		// 格式化数组
		foreach ( $current_in as $c )
		{
			$sku_value = strtoupper( $c ['sku'] );
			$result [$sku_value] ['count'] = $c ['count'];
			$result [$sku_value] ['cost'] = round($c ['cost'],2);
		}
		
		return $result;
	}
}
